/**  
 * All rights Reserved, Designed By www.tydic.com
 * @Title:  KeyPairController.java   
 * @Package com.axin.controller   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: axin     
 * @date:   2019年3月21日 下午10:33:43   
 * @version V1.0 
 * @Copyright: 2019 www.hao456.top Inc. All rights reserved. 
 */
package com.axin.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.axin.common.entity.ApiToken;
import com.axin.common.entity.JsonResult;
import com.axin.common.entity.response.TimestampResponse;
import com.axin.common.exception.SaveRuntimeException;
import com.axin.entity.HbKeyPair;
import com.axin.entity.HbUser;
import com.axin.service.CommonService;
import com.axin.service.KeyPairService;

/**   
 * @Description: TODO 
 * @ClassName:  KeyPairController
 * @author:  Axin 
 * @date:   2019年3月21日 下午10:33:43   
 * @Copyright: 2019 www.hao456.top Inc. All rights reserved. 
 */

@Controller
@RequestMapping("/keyPair")
public class KeyPairController {
	
	
	@Autowired
	private KeyPairService keyPairService;
	
	@Autowired
	private CommonService commonService;
	
	@RequestMapping("/save")
	@ResponseBody
	public JsonResult save(HbKeyPair keyPair,HttpServletRequest request){
		HbUser user = (HbUser)request.getAttribute("user");
		keyPair.setUserId(user.getId());
		Long id = null;
		try {
			id = this.keyPairService.saveKeyPair(keyPair);
		} catch (Exception e) {
			return new JsonResult(new SaveRuntimeException("保存失败!"));
		}
		HbKeyPair kPair = this.keyPairService.getKeyPairById(id);
		HttpSession session = request.getSession();
		session.setAttribute("kPair", kPair);
		return new JsonResult();
	}
	
	
	/**
	 * 获取当前用户的密钥对
	 * @Description: TODO  
	 * @Title: getKeyPair   
	 * @param request
	 * @return JsonResult
	 * @throws
	 */
	@RequestMapping("/getKeyPair")
	@ResponseBody
	public JsonResult getKeyPair(HttpServletRequest request){
		HbUser user = (HbUser)request.getAttribute("user");
		HbKeyPair keyPair = this.keyPairService.getKeyPairByUserId(user.getId());
		return new JsonResult(keyPair);
	}
	
	/**
	 * 测试密钥
	 * @Title: testKeyPair   
	 * @author: Axin
	 * @date:  2019年5月19日 下午2:39:10  
	 * @param a
	 * @param s
	 * @return
	 * @throws
	 */
	@RequestMapping("/testKeyPair")
	@ResponseBody
	public JsonResult testKeyPair(HbKeyPair keyPair){
		try {
			ApiToken token = new ApiToken(keyPair.getAccessKey(),keyPair.getSecretKey());
			TimestampResponse timestamp = this.commonService.timestamp(token);
			return new JsonResult(timestamp.getDateTime());
		} catch (Exception e) {
			return new JsonResult(new Exception("ERROR!"));
		}
		
	}

}
